package edu.jhu.cs.oose.scheduleit.backingbeans;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.jhu.cs.oose.scheduleit.services.impl.DataBaseException;
import edu.jhu.cs.oose.scheduleit.util.Attribute;
import edu.jhu.cs.oose.scheduleit.util.DateWrapper;
import edu.jhu.cs.oose.scheduleit.util.EventAttributeKind;

/**
 * This is the servlet used to communicate the AJAX component with our backing bean.
 * @author oose_group2
 *
 */
public class AjaxServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * the initiate method of the servlet
	 * @param config servlet configure setting.
	 * @throws ServletException 
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}
    
	/**
	 * the method respond to the Http 'GET' request.
	 * @param request the Http request object.
	 * @param response used to save the response to the request.
	 * @throws ServletException
	 */
	public void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			IOException {
		response.setContentType("text/xml");
		//System.out.println("receive request");
		response.setHeader("Cache-Control", "no-cache");

		PrintWriter out = response.getWriter();
		ScheduleBackingBean sbb = (ScheduleBackingBean)request.getSession(true).getAttribute("scheduleBackingBean");
		out.write(sbb.getInitXML());
		out.close();
	}
    
	/**
	 * the method respond to the Http 'POST' request.
	 * @param request the Http request object.
	 * @param response used to save the response to the request.
	 * @throws ServletException
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		System.out.println("Go AjaxServlet ");
		String type = request.getParameter("type");
		ScheduleBackingBean sbb = (ScheduleBackingBean)request.getSession(true).getAttribute("scheduleBackingBean");
		if(type.equals("update") || type.equals("add")){
			Attribute attribute = new Attribute();
			try{
				attribute.put(EventAttributeKind.START_TIME, this.generateCalendar(request.getParameter("start")));
				attribute.put(EventAttributeKind.END_TIME, this.generateCalendar(request.getParameter("end")));
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			attribute.put(EventAttributeKind.DESCRIPTION, request.getParameter("text"));
			try {
				if(type.equals("add")){
					int id = sbb.createEvent(attribute);
					//System.out.println(id);
					response.setContentType("text/xml");
					response.setHeader("Cache-Control", "no-cache");

					StringBuffer xml = new StringBuffer("<?xml version = '1.0'?>");
					xml.append("<id>"+id+"</id>");
					PrintWriter out = response.getWriter();
					out.write(xml.toString());
					out.close();
				} else {
					int id = Integer.parseInt(request.getParameter("id"));
					sbb.updateEvent(id, attribute);
				}
			} catch (DataBaseException e) {
				e.printStackTrace();
			}
		} else if(type.equals("paste")){
			response.setContentType("text/xml");
			response.setHeader("Cache-Control", "no-cache");

			StringBuffer xml = new StringBuffer("<?xml version = '1.0'?>");
			String result = null;
			try {
				result = sbb.pasteEvent();
			} catch (DataBaseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(result);
			xml.append(result);
			PrintWriter out = response.getWriter();
			out.write(xml.toString());
			out.close();
		} else{
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				if(type.equals("delete")){
					sbb.removeEvent(id);
				} else if(type.equals("copy")){
				    sbb.copyEvent(id);	
				} else {
					response.setContentType("text/xml");
					response.setHeader("Cache-Control", "no-cache");

					StringBuffer xml = new StringBuffer("<?xml version = '1.0'?>");
					String result = sbb.interactEvent(id);
					System.out.println(result);
					xml.append("<join_user>"+result+"</join_user>");
					PrintWriter out = response.getWriter();
					out.write(xml.toString());
					out.close();
				}
			} catch (DataBaseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * Create a DataWrapper object by given time expression "yyyy-mm-dd".
	 * @param s the given time expression "yyyy-mm-dd"
	 * @return The DataWrapper object
	 * @throws ParseException
	 */
	private DateWrapper generateCalendar(String s) throws ParseException{
		String[] tmp = s.split(" ");
		String[] leftPart = tmp[0].split("-");
		String[] rightPart = tmp[1].split(":");
		int year = Integer.parseInt(leftPart[0]);
		int month = Integer.parseInt(leftPart[1]);
		int date = Integer.parseInt(leftPart[2]);
		int hourOfDay = Integer.parseInt(rightPart[0]);
		int minute = Integer.parseInt(rightPart[1]);
		System.out.println("T:"+year+","+month+","+date+","+hourOfDay+","+minute);
		System.out.println("O:"+s);
		return new DateWrapper(year,month,date,hourOfDay,minute);	
	}
}
